"""
Topic管理API路由
"""
from typing import Optional
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from app.core.kafka_client import get_kafka_client
from app.utils.logger import get_logger

router = APIRouter()
logger = get_logger(__name__)


class CreateTopicRequest(BaseModel):
    """创建Topic请求"""
    name: str
    num_partitions: int = 1
    replication_factor: int = 1


class CreateTopicResponse(BaseModel):
    """创建Topic响应"""
    success: bool
    message: str
    topic_name: str


class DeleteTopicResponse(BaseModel):
    """删除Topic响应"""
    success: bool
    message: str
    topic_name: str


@router.post("/create", response_model=CreateTopicResponse)
async def create_topic(request: CreateTopicRequest):
    """创建Topic"""
    try:
        kafka_client = get_kafka_client()
        
        # 检查Topic是否已存在
        topics = await kafka_client.list_topics()
        if request.name in topics:
            raise HTTPException(status_code=400, detail=f"Topic已存在: {request.name}")
        
        # 创建Topic
        success = await kafka_client.create_topic(
            topic_name=request.name,
            num_partitions=request.num_partitions,
            replication_factor=request.replication_factor
        )
        
        if success:
            return CreateTopicResponse(
                success=True,
                message=f"Topic创建成功",
                topic_name=request.name
            )
        else:
            raise HTTPException(status_code=500, detail="Topic创建失败")
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"创建Topic失败: {e}")
        raise HTTPException(status_code=500, detail=f"创建Topic失败: {str(e)}")


@router.delete("/{topic_name}", response_model=DeleteTopicResponse)
async def delete_topic(topic_name: str):
    """删除Topic"""
    try:
        kafka_client = get_kafka_client()
        
        # 检查Topic是否存在
        topics = await kafka_client.list_topics()
        if topic_name not in topics:
            raise HTTPException(status_code=404, detail=f"Topic不存在: {topic_name}")
        
        # 删除Topic
        success = await kafka_client.delete_topic(topic_name)
        
        if success:
            return DeleteTopicResponse(
                success=True,
                message=f"Topic删除成功",
                topic_name=topic_name
            )
        else:
            raise HTTPException(status_code=500, detail="Topic删除失败")
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除Topic失败: {e}")
        raise HTTPException(status_code=500, detail=f"删除Topic失败: {str(e)}")
